package com.huilian.tool.work.weixin.service.impl;

import com.huilian.tool.common.utils.RestTemplateUtil;
import com.huilian.tool.work.weixin.dto.*;
import com.huilian.tool.work.weixin.service.ExternalContactService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 少凡
 * @Date 2022-06-27 11:52
 * version 1.0
 */
@Service
@Slf4j
public class ExternalContactServiceImpl implements ExternalContactService {


    @Resource
    private RestTemplateUtil restTemplateUtil;


    @Override
    public String getFollowUserList(String accessToken) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=")
                .append(accessToken).toString();
        return restTemplateUtil.unifyGet(url, String.class);
    }

    @Override
    public String list(String accessToken, String userId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?")
                .append("access_token=").append(accessToken)
                .append("&userid=").append(userId).append("&debug=1").toString();
        return restTemplateUtil.unifyGet(url, String.class);
    }

    @Override
    public String get(String accessToken, String externalUserId, String cursor) {
        StringBuilder url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?")
                .append("access_token=").append(accessToken)
                .append("&external_userid=").append(externalUserId);
        if (StringUtils.isNotBlank(cursor)) {
            url.append("&cursor=").append(cursor);
        }
        return restTemplateUtil.unifyGet(url.toString(), String.class);
    }

    @Override
    public String batchGetByUser(String accessToken, List<String> userIdList) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=")
                .append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("userid_list", userIdList);

        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String remark(String accessToken, ExternalContact externalContact) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=")
                .append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, externalContact, String.class);
    }

    @Override
    public String groupChatList(String accessToken, Integer limit) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getGroupChat(String accessToken, String chatId, Integer needName) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("chat_id", chatId);
        map.put("need_name", needName);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String addContactWay(String accessToken, ContactWay contactWay) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, contactWay, String.class);
    }

    @Override
    public String getContactWay(String accessToken, String configId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("config_id", configId);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String listContactWay(String accessToken, String startTime, String endTime, String cursor, Integer limit) throws ParseException {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list_contact_way?")
                .append("access_token=").append(accessToken).toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isNotBlank(startTime)) {
            calendar.setTime(sdf.parse(startTime));
            map.put("start_time", calendar.getTimeInMillis() / 1000L);
        }
        if (StringUtils.isNotBlank(endTime)) {
            calendar.setTime(sdf.parse(endTime));
            map.put("end_time", calendar.getTimeInMillis() / 1000L);
        }
        map.put("cursor", cursor);
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String updateContactWay(String accessToken, ContactWay contactWay) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, contactWay, String.class);
    }

    @Override
    public String delContactWay(String accessToken, String configId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("config_id", configId);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }


    @Override
    public String addMomentTask(String accessToken, Moment moment) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_moment_task?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, moment, String.class);
    }

    @Override
    public String getMomentTaskResult(String accessToken, String jobId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_task_result?")
                .append("access_token=").append(accessToken)
                .append("&jobid=").append(jobId)
                .toString();
        return restTemplateUtil.unifyGet(url, String.class);
    }

    @Override
    public String getMomentList(String accessToken, String startTime, String endTime, String creator, String cursor, Integer limit) throws ParseException {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_list?")
                .append("access_token=").append(accessToken).toString();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, Object> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf.parse(startTime));
        map.put("start_time", calendar.getTimeInMillis() / 1000L);
        calendar.setTime(sdf.parse(endTime));
        map.put("end_time", calendar.getTimeInMillis() / 1000L);
        map.put("creator", creator);
        map.put("filter_type", 2);
        map.put("cursor", cursor);
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getMomentTask(String accessToken, String momentId, String cursor, Integer limit) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_task?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("moment_id", momentId);
        map.put("cursor", cursor);
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getMomentCustomerList(String accessToken, String momentId, String userId, String cursor, Integer limit) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_customer_list?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("moment_id", momentId);
        map.put("userid", userId);
        map.put("cursor", cursor);
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getMomentSendResult(String accessToken, String momentId, String userId, String cursor, Integer limit) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_send_result?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("moment_id", momentId);
        map.put("userid", userId);
        map.put("cursor", cursor);
        map.put("limit", limit);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getMomentComments(String accessToken, String momentId, String userId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_comments?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("moment_id", momentId);
        map.put("userid", userId);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String addMsgTemplate(String accessToken, MsgTemplate msgTemplate) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, msgTemplate, String.class);
    }

    @Override
    public String getGroupMsgListV2(String accessToken, QueryParamGroupMsg queryParam) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_list_v2?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParam, String.class);
    }

    @Override
    public String getGroupMsgTask(String accessToken, QueryParamGroupMsg queryParam) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_task?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParam, String.class);
    }

    @Override
    public String getGroupMsgSendResult(String accessToken, QueryParamGroupMsg queryParam) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_send_result?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParam, String.class);
    }

    @Override
    public String sendWelcomeMsg(String accessToken, MsgTemplate msgTemplate) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, msgTemplate, String.class);
    }

    /**
     * 添加入群欢迎语素材
     * @param accessToken
     * @param groupWelcome
     * @return
     */
    @Override
    public String groupWelcomeTemplateAdd(String accessToken, GroupWelcome groupWelcome) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?")
                .append("access_token=").append(accessToken).toString();

        return restTemplateUtil.unifyPost(url, groupWelcome, String.class);
    }

    @Override
    public String uploadimg(String accessToken,String fileUrl) throws Exception {
        //定义一个URL对象
        URL url = new URL(fileUrl);
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] bytesArray = readInputStream(inStream);

        String httpMethod = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type=image";   //临时图片 3天有效
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
            @Override
            public String getFilename() {
                return "img";
            }
        };
        paramMap.add("miniprogramlogo", contentsAsResource);
        String json = restTemplate.postForObject(httpMethod, paramMap, String.class);
        log.info("上传图片素材:{}",json);
        return json;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    @Override
    public String groupWelcomeTemplateEdit(String accessToken, Attachment attachment) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, attachment, String.class);
    }

    @Override
    public String groupWelcomeTemplateGet(String accessToken, String templateId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/get?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("template_id", templateId);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String groupWelcomeTemplateDel(String accessToken, String templateId) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/del?")
                .append("access_token=").append(accessToken).toString();
        Map<String, Object> map = new HashMap<>();
        map.put("template_id", templateId);
        return restTemplateUtil.unifyPost(url, map, String.class);
    }

    @Override
    public String getUserBehaviorData(String accessToken, QueryParamStats queryParamStats) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParamStats, String.class);
    }

    @Override
    public String groupChatStatistic(String accessToken, QueryParamStats queryParamStats) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParamStats, String.class);
    }

    @Override
    public String groupChatStatisticGroupByDay(String accessToken, QueryParamStats queryParamStats) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic_group_by_day?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, queryParamStats, String.class);
    }

    @Override
    public String addGroupWelcomeTemplate(String accessToken,GroupWelcome groupWelcome) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, groupWelcome, String.class);
    }

    @Override
    public String editGroupWelcomeTemplate(String accessToken,GroupWelcome groupWelcome) {
        String url = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?")
                .append("access_token=").append(accessToken).toString();
        return restTemplateUtil.unifyPost(url, groupWelcome, String.class);
    }
}
